<script setup>
  import {
    ref,
    computed,
    onMounted
  } from 'vue'
  import {
    ElMessage,
    ElMessageBox 
  } from 'element-plus'
  import {
    Edit,
    Delete,
    Plus,
    View
  } from '@element-plus/icons-vue'
  import {
    getUserList,
    updateUserInfo,
    updateUserStatus,
    addUser
  } from '@/api/user'


  
  const users = ref([{
    studentId: '',
    name: '',
    gender: '',
    address: '',
    role: '',
    birthDate: '',
    idCardNumber: '',
    college: '',
    major: '',
    className: '',
    status: '',
    dormId: '',
    bedNumber: '',
    phone: '',
    email: '',
    emergencyContact: '',
    username: '',
    password: '',
    building: '',
    floor: '',
    dormNumber: ''
  }])
  const searchUsername = ref('')
  const searchAddress = ref('')
  //规则校验
const rules = {
  studentId: [{ required: false }],
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idCardNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  college: [{ required: true, message: '请输入学院', trigger: 'blur' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  className: [{ required: true, message: '请输入班级', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入生源地', trigger: 'blur' }]
}

const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

  //通过函数获取用户列表
  const getUserListApi = async () => {
    const res = await getUserList(currentPage.value, pageSize.value,searchUsername.value,searchAddress.value)

    users.value = res.data.items
    total.value = res.data.total
    ElMessage.success('获取用户列表成功')
  }
  getUserListApi()
  // 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  getUserListApi()
}

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getUserListApi()
}
  //弹窗状态
  const DialogVisible = ref(false)
  //弹窗数据模型
  const userFormData = ref({
    studentId: '',
    name: '',
    gender: '',
    address: '',
    birthDate: '',
    idCardNumber: '',
    college: '',
    major: '',
    className: '',
    status: '',
    bedNumber: '',
    phone: '',
    email: '',
    emergencyContact: '',
    username: '',
    password: ''
  })
  // 详情对话框状态
  const detailDialogVisible = ref(false)
  // 查看用户详情
  const viewUserDetail = (user) => {
    detailDialogVisible.value = true
    userFormData.value = { ...user }
  }
  //弹窗标题
  const title = ref('')
  const editUser = (user) => {
    // 打开编辑用户信息的对话框
    // 这里可以使用 Element Plus 的 Dialog 组件来实现
    title.value = '编辑用户'
    DialogVisible.value = true
    userFormData.value = {
      ...user
    }
    openEditDialog(user)
  }

  // 修改保存方法
  const saveUserInfo = async () => {
    try {
      const updatedUser = {
        studentId: userFormData.value.studentId,
        name: userFormData.value.name,
        gender: userFormData.value.gender,
        address: userFormData.value.address,
        birthDate: userFormData.value.birthDate,
        idCardNumber: userFormData.value.idCardNumber,
        college: userFormData.value.college,
        major: userFormData.value.major,
        className: userFormData.value.className,
        status: userFormData.value.status,
        bedNumber: userFormData.value.bedNumber,
        phone: userFormData.value.phone,
        email: userFormData.value.email,
        emergencyContact: userFormData.value.emergencyContact,
        username: userFormData.value.username,
        password: userFormData.value.password
      }
      // 更新用户信息
      await updateUserInfo(updatedUser)
      ElMessage.success('用户信息更新成功')
      DialogVisible.value = false
      getUserListApi()
    } catch (error) {
      ElMessage.error('用户信息更新失败')
    }
  }
  //新增学生 
  const AddUser = async() => {
    try {
        const userInfo = userFormData.value
        // 设置默认角色为普通用户
        userInfo.role = 'student'
        // 移除学号字段，由后端自动生成
        delete userInfo.studentId
        const res = await addUser(userInfo)
        ElMessage.success(res.message || '新增学生成功')
        DialogVisible.value = false
        getUserListApi()
    } catch (error) {
      ElMessage.error(error.message || '新增学生失败')
    }
  }
  //修改学生账号状态
  const updateStudentStatus = async(studentId,status)=>{
    if(status === '禁用'){
      const res = await updateUserStatus(studentId,status)
      ElMessage.success('用户状态更新成功')
      getUserListApi()
      return
    }
    if(status === '正常'){
      status = '正常'
      const res = await updateUserStatus(studentId,status) 
      ElMessage.success('用户状态更新成功')
      getUserListApi()
      return
    }
    ElMessage.error('用户状态更新失败')
  }

  
  //清空模型
const clear = () => {
  userFormData.value = {
    studentId: '',
    name: '',
    gender: '',
    address: '',
    role: '',
    birthDate: '',
    idCardNumber: '',
    college: '',
    major: '',
    className: '',
    Status: '正常',
    dormId: '',
    bedNumber: '',
    phone: '',
    email: '',
    emergencyContact: '',
    username: '',
    password: '',
    building: '',
    floor: '',
    dormNumber: ''
  }
}
</script>

<template>
  <div class="user-container">
    <div class="header-actions">
      <div class="search-section">
        <el-input v-model="searchUsername" placeholder="搜索学生账号" style="width: 200px; margin-right: 10px" clearable />
        <el-input v-model="searchAddress" placeholder="搜索生源地" style="width: 200px; margin-right: 10px" clearable />
        <el-button type="primary" @click="getUserListApi">搜索</el-button>
      </div>
      <el-button type="primary" :icon="Plus" @click="DialogVisible=true;title='新增用户';clear()">新增用户</el-button>
    </div>
    <el-table :data="users" style="width: 100%; margin-top: 20px">
      <el-table-column prop="studentId" label="学号" min-width="160" />
      <el-table-column prop="username" label="账号" min-width="100" />
      <el-table-column prop="name" label="姓名" min-width="80" />
      <el-table-column prop="gender" label="性别" min-width="60" />
      <el-table-column prop="college" label="学院" min-width="100" />
      <el-table-column prop="phone" label="电话" min-width="120" />
      <el-table-column prop="address" label="生源地" min-width="100" />
      <el-table-column prop="Status" label="状态" min-width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === '正常' ? 'success' : 'danger'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140">
        <template #default="{ row }">
          <el-tooltip placement="top">
            <template #content>学生详情信息</template>
            <el-link type="primary"  @click="viewUserDetail(row)">查看</el-link>
          </el-tooltip>
          <el-tooltip placement="top">
            <template #content>编辑学生信息</template>
            <el-link type="success" @click="editUser(row)">编辑</el-link>
          </el-tooltip>
          
          <el-link type="danger"  @click="updateStudentStatus(row.studentId,'禁用')">禁用</el-link>
          <el-link type="success"  @click="updateStudentStatus(row.studentId,'正常')">启用</el-link>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[2, 5, 10, 15]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    <!-- Edit Dialog -->
    <el-dialog v-model="DialogVisible" :title="title" >

      <el-form :model="userFormData" :rules="rules">
        <el-form-item label="学号" prop="studentId" required v-if="title === '编辑用户'">
          <el-input v-model="userFormData.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username" required>
          <el-input v-model="userFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="userFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" required>
          <el-select v-model="userFormData.gender" style="width: 100%">
            <el-option label="男" value="男"/>
            <el-option label="女" value="女"/>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate" required>
          <el-date-picker v-model="userFormData.birthDate" type="date" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber" required>
          <el-input v-model="userFormData.idCardNumber"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="college" required>
          <el-input v-model="userFormData.college"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major" required>
          <el-input v-model="userFormData.major"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className" required>
          <el-input v-model="userFormData.className"></el-input>
        </el-form-item>
        <el-form-item label="床位号" prop="bedNumber">
          <el-input v-model="userFormData.bedNumber"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone" required>
          <el-input v-model="userFormData.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="userFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="userFormData.emergencyContact"></el-input>
        </el-form-item>
        <el-form-item label="生源地" prop="address" required>
          <el-input v-model="userFormData.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="DialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title==='新增用户'?AddUser():saveUserInfo()">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Detail Dialog -->
    <el-dialog v-model="detailDialogVisible" title="学生详情" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ userFormData.studentId }}</el-descriptions-item>
        <el-descriptions-item label="账号">{{ userFormData.username }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ userFormData.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ userFormData.gender }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ userFormData.birthDate }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ userFormData.idCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="学院">{{ userFormData.college }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ userFormData.major }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ userFormData.className }}</el-descriptions-item>
        <el-descriptions-item label="宿舍楼">{{ userFormData.building }}</el-descriptions-item>
        <el-descriptions-item label="宿舍号">{{ userFormData.dormNumber }}</el-descriptions-item>
        <el-descriptions-item label="床位号">{{ userFormData.bedNumber }}</el-descriptions-item>
        <el-descriptions-item label="电话">{{ userFormData.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userFormData.email }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系人">{{ userFormData.emergencyContact }}</el-descriptions-item>
        <el-descriptions-item label="生源地">{{ userFormData.address }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="userFormData.status === '正常' ? 'success' : 'danger'">
            {{ userFormData.status }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
  .el-link{
    margin-left: 8px;
  }
  .user-container {
    padding: 20px;
  }

  .header-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .avatar-uploader {
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }

  .avatar-uploader:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar-preview {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
</style>
